/**
 *  julive
 *
 *  Create by songli on 2021/07/07
 *  Copyright © 2021 居理买房网. All rights reserved.
 */

package domain

import (
	"context"

	"github.com/grpc-ecosystem/go-grpc-middleware/logging/zap/ctxzap"
	"github.com/spf13/viper"
	"go.uber.org/zap"

	"git.julive.com/julive/shorturl/server/model"
	"git.julive.com/julive/shorturl/server/proto/shorturl"
	"git.julive.com/julive/shorturl/server/repository"
	"git.julive.com/micro/pkg/dao"
)

type ShorturlDomain interface {
	CreateShorturl(ctx context.Context, path, url string) (*shorturl.Shorturl, error)
	GetLongurl(ctx context.Context, path, url string) (*shorturl.Longurl, error)
}

type shorturlDomain struct {
	dao.Cache

	repo repository.ShorturlRepository
}

func NewShorturlDomain() ShorturlDomain {
	repo := repository.NewShorturlRepository()
	dm := &shorturlDomain{
		Cache: dao.NewCache(),
		repo:  repo}
	return dm
}

func (dm *shorturlDomain) CreateShorturl(ctx context.Context, path, url string) (*shorturl.Shorturl, error) {
	logger := ctxzap.Extract(ctx).With(zap.String("layer", "shorturlDomain"), zap.String("func", "CreateShorturl"))
	maxTry := viper.GetInt("server.retry")
	if maxTry <= 0 {
		maxTry = 1
	}
	m, maxTry, err := dm.repo.CreateShorturl(ctx, path, url, maxTry)
	if err != nil {
		logger.Error("dm.repo.CreateShorturl error", zap.Int("retry", maxTry), zap.Error(err))
	}
	return ShorturlPtod(m), err
}

func (dm *shorturlDomain) GetLongurl(ctx context.Context, path, url string) (*shorturl.Longurl, error) {
	m, err := dm.repo.GetShorturl(ctx, path, url)
	return LongurlPtod(m), err
}

func ShorturlPtod(po *model.UrlMainShard) *shorturl.Shorturl {
	if po == nil {
		return nil
	}

	dto := &shorturl.Shorturl{}
	dto.Shorturl = po.ShortUrl
	return dto
}

func LongurlPtod(po *model.UrlMainShard) *shorturl.Longurl {
	if po == nil {
		return nil
	}

	dto := &shorturl.Longurl{}
	dto.Longurl = po.LongUrl
	return dto
}
